package dao;

import JDBC.Util.IRowMapper;
import JDBC.Util.JDBCTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pojo.Student;

import java.sql.*;
import java.util.List;

public class StudentDao {

//    private Logger logger = LoggerFactory.getLogger(StudentDao.class);


    //添加学生信息
    public void add(Student stu){
        String sql = "insert into t_student(name,age) values(?,?)";
        Object[] params = new Object[]{stu.getName(),stu.getAge()};
        JDBCTemplate.update(sql,params);
    }

    //删除学生信息
    public void delete(int id){
        String sql = "delete from t_student where id=?";
        JDBCTemplate.update(sql,id);
    }

    //修改学生信息
    public void update(Student stu){
        String sql = "update t_student set name =?,age=? where id=?";
        Object[] params = new Object[]{stu.getName(),stu.getAge(),stu.getId()};
        JDBCTemplate.update(sql,params);
    }

    //查询
    public Student get(int id){
        String sql = "select * from t_student where id=?";
        List<Student> list = JDBCTemplate.query(sql, new StudentRowMapper(),id);
        return list.size()>0?list.get(0):null;
    }

    //查询
    public List<Student> list(){
        String sql = "select * from t_student";
        return JDBCTemplate.query(sql,new StudentRowMapper());
    }

    public int getCount(){
         String sql = "select count(*) total from t_student";
         int totalCount = (int)JDBCTemplate.query(sql, new IRowMapper<Integer>() {
             public Integer mapping(ResultSet rs) throws Exception{
                Integer totalCount = null;
                if(rs.next()){
                    totalCount = rs.getInt("total");
                }
                return totalCount;
             }
         });

         return totalCount;
    }
}
